package com.jy.appmarket.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import android.text.TextUtils;

public class IOTools {
	private static final String TAG = IOTools.class.getSimpleName();

	public static void safeClose(Closeable c) {
		if (c == null) {
			return;
		}
		try {
			c.close();
		} catch (IOException e) {
			// do nothing
		}
	}

	public static void copyStream(InputStream is, OutputStream os) throws IOException {
		final int buffer_size = 1024;
		byte[] bytes = new byte[buffer_size];
		while (true) {
			int count = is.read(bytes, 0, buffer_size);
			if (count == -1)
				break;
			os.write(bytes, 0, count);
		}
	}

	public static String inputStream2String(InputStream is) {
		if (is == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (UnsupportedEncodingException e1) {
			LogUtil.e(TAG, "UnsupportedEncodingException in inputStream2String!");
		} catch (IOException e) {
			LogUtil.e(TAG, "IOException in inputStream2String!");
		}

		return sb.toString();
	}

	public static InputStream String2InputStream(String str) {
		InputStream is = null;

		if (TextUtils.isEmpty(str)) {
			return null;
		}

		try {
			is = new ByteArrayInputStream(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			LogUtil.e(TAG, "UnsupportedEncodingException in String2InputStream!");
		}
		return is;
	}
}
